#' Preprocess JIP-Test Parameters for PCA 
#' Returns SOURCE (from jip_test() output) + clean numeric parameters (no NA/Inf)
#'
#' @param jip_data Data frame from \code{jip_test()} (contains SOURCE and numeric parameters)
#' @return Data frame with:
#'   - First column: Original SOURCE (from your data files)
#'   - Remaining columns: Numeric JIP parameters (no NA/Inf)
#' @export
jip_pca = function(jip_data) {
  # Force base R data frame (avoid data.table conflicts)
  if (inherits(jip_data, "data.table")) {
    jip_data = as.data.frame(jip_data)
  }
  
  # 1. Validate SOURCE column exists (from jip_test() output)
  if (!"SOURCE" %in% colnames(jip_data)) {
    stop("jip_data must contain a 'SOURCE' column (from jip_test() output)")
  }
  
  # 2. Separate SOURCE (original file names) and numeric parameters
  source_col = jip_data[, "SOURCE", drop = FALSE]  # Preserve original SOURCE
  numeric_cols = sapply(jip_data, is.numeric)     # Identify numeric parameters
  numeric_data = jip_data[, numeric_cols, drop = FALSE]
  
  # 3. Clean numeric data (remove rows with NA/Inf)
  # Remove rows with NA in numeric parameters
  valid_rows = complete.cases(numeric_data)
  if (sum(!valid_rows) > 0) {
    message(sprintf("Removing %d rows with missing numeric values", sum(!valid_rows)))
  }
  numeric_data_clean = numeric_data[valid_rows, , drop = FALSE]
  source_clean = source_col[valid_rows, , drop = FALSE]
  
  # Remove columns with infinite values (if any)
  inf_cols = sapply(numeric_data_clean, function(col) any(is.infinite(col)))
  if (sum(inf_cols) > 0) {
    message(sprintf("Removing %d columns with infinite values", sum(inf_cols)))
    numeric_data_clean = numeric_data_clean[, !inf_cols, drop = FALSE]
  }
  
  # 4. Final validation (enough samples/variables for PCA)
  if (nrow(numeric_data_clean) < 2) stop("Not enough samples left (need ≥2)")
  if (ncol(numeric_data_clean) < 2) stop("Not enough numeric parameters (need ≥2)")
  
  # 5. Combine SOURCE + clean numeric data 
  cbind(source_clean, numeric_data_clean)
}

